<template>
  <div class="interview-report-page">
    <a-card :bordered="false" :loading="loading">
      <!-- 头部操作栏 -->
      <div class="page-header">
        <a-space>
          <a-button @click="goBack">
            <template #icon>
              <ArrowLeftOutlined />
            </template>
            返回
          </a-button>
          <a-button type="primary" @click="exportPDF" :loading="exporting">
            <template #icon>
              <FilePdfOutlined />
            </template>
            导出PDF
          </a-button>
        </a-space>
      </div>

      <!-- 报告内容 -->
      <div ref="reportContent" class="report-content" :class="{ 'pdf-mode': isPdfExporting }" v-if="report">
        <!-- 报告标题 -->
        <div class="report-title">
          <h1>面试报告</h1>
          <p class="report-meta">
            <span>岗位：{{ report.interviewType }}</span>
            <a-divider type="vertical" />
            <span>面试时间：{{ formatTime(report.createTime) }}</span>
          </p>
        </div>

        <!-- 综合评分 -->
        <a-card class="score-card" :bordered="false">
          <div class="score-section">
            <div class="score-circle">
              <a-progress
                type="circle"
                :percent="report.interviewScore || 0"
                :width="150"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
              >
                <template #format="percent">
                  <div class="score-text">
                    <div class="score-number">{{ percent }}</div>
                    <div class="score-label">综合评分</div>
                  </div>
                </template>
              </a-progress>
            </div>
            <div class="score-details">
              <a-descriptions :column="1" bordered>
                <a-descriptions-item label="优势">
                  {{ report.strengths || '暂无' }}
                </a-descriptions-item>
                <a-descriptions-item label="存在的问题">
                  {{ report.existingProblem || '暂无' }}
                </a-descriptions-item>
                <a-descriptions-item label="提升建议">
                  {{ report.improvementSuggestion || '暂无' }}
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </div>
        </a-card>

        <!-- 综合能力分析（雷达图） -->
        <a-card title="综合能力分析" class="chart-card" :bordered="false">
          <div ref="radarChart" class="radar-chart"></div>
        </a-card>

        <!-- 题目详情 -->
        <a-card title="题目详情" :bordered="false" class="questions-card">
          <a-collapse v-if="!isPdfExporting" v-model:activeKey="activeKeys" accordion>
            <a-collapse-panel
              v-for="(question, index) in report.interviewQuestions"
              :key="index"
              :header="`第 ${index + 1} 题：${question.questionName}`"
            >
              <div class="question-detail">
                <div class="detail-item">
                  <h4><CheckCircleOutlined style="color: #52c41a" /> 标准答案</h4>
                  <p class="answer-text">{{ question.standardAnswer || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><EditOutlined style="color: #1890ff" /> 您的回答</h4>
                  <p class="answer-text">{{ question.userAnswer || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><StarOutlined style="color: #faad14" /> 回答优势</h4>
                  <p class="answer-text">{{ question.responseStrengths || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><WarningOutlined style="color: #ff4d4f" /> 回答缺陷</h4>
                  <p class="answer-text">{{ question.responseDefect || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><BulbOutlined style="color: #722ed1" /> 提升建议</h4>
                  <p class="answer-text">{{ question.improvementSuggestion || '暂无' }}</p>
                </div>
              </div>
            </a-collapse-panel>
          </a-collapse>

          <!-- PDF模式：展开所有题目 -->
          <div v-else class="pdf-questions">
            <div v-for="(question, index) in report.interviewQuestions" :key="index" class="pdf-question-item">
              <h3 class="pdf-question-title">第 {{ index + 1 }} 题：{{ question.questionName }}</h3>
              <div class="question-detail">
                <div class="detail-item">
                  <h4><CheckCircleOutlined style="color: #52c41a" /> 标准答案</h4>
                  <p class="answer-text">{{ question.standardAnswer || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><EditOutlined style="color: #1890ff" /> 您的回答</h4>
                  <p class="answer-text">{{ question.userAnswer || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><StarOutlined style="color: #faad14" /> 回答优势</h4>
                  <p class="answer-text">{{ question.responseStrengths || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><WarningOutlined style="color: #ff4d4f" /> 回答缺陷</h4>
                  <p class="answer-text">{{ question.responseDefect || '暂无' }}</p>
                </div>
                <a-divider />
                <div class="detail-item">
                  <h4><BulbOutlined style="color: #722ed1" /> 提升建议</h4>
                  <p class="answer-text">{{ question.improvementSuggestion || '暂无' }}</p>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  FilePdfOutlined,
  CheckCircleOutlined,
  EditOutlined,
  StarOutlined,
  WarningOutlined,
  BulbOutlined,
} from '@ant-design/icons-vue'
import * as echarts from 'echarts'
import html2pdf from 'html2pdf.js'
import { getReportById } from '@/api/interviewReportController'

const router = useRouter()
const route = useRoute()

// 数据
const loading = ref(false)
const exporting = ref(false)
const isPdfExporting = ref(false)
const report = ref<any>(null)
const reportContent = ref<HTMLElement>()
const radarChart = ref<HTMLElement>()
const activeKeys = ref<string[]>([])

let chartInstance: echarts.ECharts | null = null

// 加载报告详情
const loadReport = async () => {
  try {
    loading.value = true
    const reportIdStr = route.params.id as string

    if (!reportIdStr) {
      message.error('报告ID不存在')
      router.push('/interview')
      return
    }

    // 使用字符串形式传递，避免大数字精度丢失
    // @ts-ignore - TypeScript定义为number，但实际HTTP请求会序列化为字符串
    const res = await getReportById({ id: reportIdStr })

    if (res.data.code === 0 && res.data.data) {
      report.value = res.data.data

      // 等待DOM更新后渲染图表
      nextTick(() => {
        renderRadarChart()
      })
    } else {
      message.error('加载报告失败：' + res.data.message)
    }
  } catch (error) {
    message.error('加载报告失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 渲染雷达图
const renderRadarChart = () => {
  if (!radarChart.value || !report.value) return

  // 销毁旧实例
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(radarChart.value)

  // 从维度列表中提取数据
  const dimensionList = report.value.dimensionScores || []

  const indicator = dimensionList.map((dim: any) => ({
    name: dim.dimensionType,
    max: 100,
  }))

  const values = dimensionList.map((dim: any) => dim.score || 0)

  const option = {
    title: {
      text: '能力维度评分',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    radar: {
      indicator: indicator.length > 0 ? indicator : [
        { name: '基础知识', max: 100 },
        { name: '实践能力', max: 100 },
        { name: '问题解决', max: 100 },
        { name: '沟通表达', max: 100 },
        { name: '思维逻辑', max: 100 },
      ],
      shape: 'polygon',
      radius: '60%',
    },
    series: [
      {
        name: '能力评分',
        type: 'radar',
        data: [
          {
            value: values.length > 0 ? values : [70, 80, 75, 85, 78],
            name: '综合能力',
            areaStyle: {
              color: 'rgba(24, 144, 255, 0.2)',
            },
            lineStyle: {
              color: '#1890ff',
            },
            itemStyle: {
              color: '#1890ff',
            },
          },
        ],
      },
    ],
  }

  chartInstance.setOption(option)
}

// 导出PDF
const exportPDF = async () => {
  if (!reportContent.value || !radarChart.value) return

  try {
    exporting.value = true
    message.loading('正在生成PDF...', 0)

    // 创建遮罩层，避免用户看到CSS变化
    const mask = document.createElement('div')
    mask.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(255, 255, 255, 0.9);
      z-index: 9999;
      display: flex;
      align-items: center;
      justify-content: center;
    `
    document.body.appendChild(mask)

    // 将雷达图转换为图片
    let chartImageUrl = ''
    if (chartInstance) {
      chartImageUrl = chartInstance.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      })

      // 临时替换图表为图片
      const chartContainer = radarChart.value
      const originalChart = chartContainer.innerHTML
      chartContainer.innerHTML = `<img src="${chartImageUrl}" style="width: 100%; height: 280px; object-fit: contain;" />`

      // 等待图片加载
      await new Promise(resolve => setTimeout(resolve, 100))
    }

    // 切换到PDF模式
    isPdfExporting.value = true
    await nextTick()
    await new Promise(resolve => setTimeout(resolve, 200))

    const opt = {
      margin: 10,
      filename: `面试报告_${report.value?.interviewType}_${Date.now()}.pdf`,
      image: { type: 'jpeg' as const, quality: 0.95 },
      html2canvas: {
        scale: 2,
        useCORS: true,
        logging: false,
        backgroundColor: '#ffffff',
        allowTaint: true
      },
      jsPDF: {
        unit: 'mm',
        format: 'a4',
        orientation: 'portrait' as const
      }
    }

    await html2pdf().set(opt).from(reportContent.value).save()

    message.destroy()
    message.success('PDF导出成功')
  } catch (error) {
    message.destroy()
    message.error('PDF导出失败')
    console.error(error)
  } finally {
    // 恢复PDF模式和遮罩
    isPdfExporting.value = false
    exporting.value = false

    // 恢复雷达图
    if (chartInstance) {
      await nextTick()
      renderRadarChart()
    }

    // 移除遮罩
    const mask = document.querySelector('div[style*="z-index: 9999"]')
    if (mask) {
      document.body.removeChild(mask)
    }
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  return time.replace('T', ' ')
}

// 返回
const goBack = () => {
  router.push('/interview')
}

onMounted(() => {
  loadReport()
})
</script>

<style scoped>
.interview-report-page {
  padding: 24px;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 8%, #e2e8f0 20%, #cbd5e1 100%),
    radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.12) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(16, 185, 129, 0.08) 0%, transparent 50%);
  min-height: calc(100vh - 64px);
}

:deep(.ant-card) {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.page-header {
  margin-bottom: 24px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.page-header .ant-btn {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
}

.page-header .ant-btn-primary {
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
  border: none;
}

.report-content {
  max-width: 1200px;
  margin: 0 auto;
}

.report-title {
  text-align: center;
  margin-bottom: 32px;
  padding: 32px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.report-title h1 {
  font-size: 36px;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 50%, #10b981 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 16px;
}

.report-meta {
  font-size: 16px;
  color: #666;
}

.report-meta span {
  margin: 0 8px;
}

.score-card {
  margin-bottom: 24px;

  color: #fff;
  border-radius: 16px;
  overflow: hidden;
}

:deep(.score-card .ant-card-body) {
  padding: 32px;
}

.score-section {
  display: flex;
  gap: 40px;
  align-items: center;
}

.score-circle {
  flex-shrink: 0;
}

.score-text {
  text-align: center;
}

.score-number {
  font-size: 36px;
  font-weight: 700;
  color: #52c41a;
}

.score-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.8);
  margin-top: 8px;
}

.score-details {
  flex: 1;
}

:deep(.score-card .ant-descriptions) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  overflow: hidden;
}

:deep(.score-card .ant-descriptions-item-label) {
  font-weight: 600;
  background: #f5f7fa;
}

:deep(.score-card .ant-descriptions-item-content) {
  color: #333;
}

.chart-card {
  margin-bottom: 24px;
}

:deep(.chart-card .ant-card-head) {
  border-bottom: 2px solid #f0f0f0;
  font-weight: 600;
  font-size: 18px;
}

.radar-chart {
  width: 100%;
  height: 400px;
}

.questions-card {
    margin-top: 84px;
  margin-bottom: 24px;
}

:deep(.questions-card .ant-card-head) {

  border-bottom: 2px solid #f0f0f0;
  font-weight: 600;
  font-size: 18px;
}

:deep(.ant-collapse) {

  border-radius: 8px;
  border: none;
  background: transparent;
}

:deep(.ant-collapse-item) {
  margin-bottom: 12px;
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
  border: 1px solid #e8edf2;
}

:deep(.ant-collapse-header) {
  font-weight: 600;
  font-size: 16px;
  padding: 16px 20px;
  background: #f5f7fa;
}

:deep(.ant-collapse-content) {
  border-top: 1px solid #e8edf2;
}

:deep(.ant-collapse-content-box) {
  padding: 20px;
}

.question-detail {
  padding: 0;
}

.detail-item {
  margin-bottom: 20px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item h4 {

  font-size: 15px;
  font-weight: 600;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
}

.answer-text {
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
  border-radius: 8px;
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
  border-left: 3px solid #3b82f6;
}

:deep(.ant-divider) {
  margin: 16px 0;
}

/* PDF模式样式 */
.report-content.pdf-mode {
  background: white !important;
  max-width: 100% !important;
  padding: 0 !important;
}

.report-content.pdf-mode .ant-card {
  border: 1px solid #e8e8e8 !important;
  box-shadow: none !important;
  background: white !important;
  margin-bottom: 12px !important;
  page-break-inside: avoid;
  border-radius: 4px !important;
}

.report-content.pdf-mode .ant-card-head {
  background: white !important;
  border-bottom: 2px solid #1890ff !important;
  padding: 10px 14px !important;
  min-height: auto !important;
}

.report-content.pdf-mode .ant-card-head-title {
  font-size: 16px !important;
  font-weight: 600 !important;
  padding: 0 !important;
}

.report-content.pdf-mode .ant-card-body {
  padding: 14px !important;
}

.report-content.pdf-mode .ant-divider {
  margin: 8px 0 !important;
}

/* PDF模式：移除report-title的渐变背景 */
.report-content.pdf-mode .report-title {
  background: white !important;
  box-shadow: none !important;
  border: 1px solid #e8e8e8 !important;
  margin-bottom: 12px !important;
  padding: 16px !important;
  border-radius: 4px !important;
  text-align: center !important;
}

.report-content.pdf-mode .report-title h1 {
  background: none !important;
  background-clip: unset !important;
  -webkit-background-clip: unset !important;
  -webkit-text-fill-color: #1890ff !important;
  color: #1890ff !important;
  font-size: 24px !important;
  margin-bottom: 10px !important;
  font-weight: 600 !important;
}

.report-content.pdf-mode .report-meta {

  font-size: 13px !important;
  color: #666 !important;
  margin: 0 !important;
}

.report-content.pdf-mode .report-meta span {
  margin: 0 6px !important;
}

/* PDF模式：移除score-card的渐变背景 */
.report-content.pdf-mode .score-card {
  background: white !important;
}

.report-content.pdf-mode .score-section {
  gap: 20px !important;
}

.report-content.pdf-mode .score-card .ant-progress {
  margin: 0 !important;
}

.report-content.pdf-mode .score-card .score-text {
  margin: 0 !important;
}

.report-content.pdf-mode .score-card .score-number {
  color: #1890ff !important;
  font-size: 32px !important;
  font-weight: normal !important;
}

.report-content.pdf-mode .score-card .score-label {
  font-size: 12px !important;
  color: #666 !important;
  font-weight: normal !important;
}

.report-content.pdf-mode .score-card .ant-descriptions {
  background: white !important;
  border: 1px solid #e8e8e8 !important;
}

.report-content.pdf-mode .score-card .ant-descriptions-item-label {
  background: #f5f7fa !important;
  font-size: 13px !important;
  font-weight: normal !important;
  padding: 8px 12px !important;
}

.report-content.pdf-mode .score-card .ant-descriptions-item-content {
  font-size: 12px !important;
  padding: 8px 12px !important;
  line-height: 1.6 !important;
  font-weight: normal !important;
}

/* PDF模式：雷达图优化 */
.report-content.pdf-mode .chart-card {
  page-break-inside: avoid;
  min-height: auto !important;
}

.report-content.pdf-mode .chart-card .ant-card-head-title {
  font-size: 16px !important;
  font-weight: 600 !important;
}

.report-content.pdf-mode .radar-chart {
  height: 280px !important;
  width: 100% !important;
  margin: 0 auto !important;
}

/* PDF模式：题目详情不独占页面 */
.report-content.pdf-mode .questions-card {
    margin-top: 100px;
  page-break-before: auto !important;
}

.pdf-questions {
  display: block;
}

.pdf-question-item {
    margin-top: 20px;
  margin-bottom: 15px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: #fafafa;
  page-break-inside: avoid;
}

.pdf-question-item:last-child {
  margin-bottom: 0;
}

.pdf-question-title {
  font-size: 14px;
  font-weight: 600;
  color: #1890ff;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #d9d9d9;
}

.report-content.pdf-mode .detail-item h4 {
  font-size: 13px !important;
  margin-bottom: 8px !important;
  font-weight: normal !important;
}

.report-content.pdf-mode .answer-text {
  padding: 10px !important;
  font-size: 12px !important;
  line-height: 1.6 !important;
  background: white !important;
  border: 1px solid #e8e8e8 !important;
  font-weight: normal !important;
}

/* 打印优化 */
@media print {
  .page-header,
  .ant-back-top {
    display: none !important;
  }

  .interview-report-page {
    background: white !important;
  }

  .report-content {
    background: white !important;
    box-shadow: none !important;
  }

  .pdf-question-item {
    page-break-inside: avoid;
  }
}

/* 响应式样式 */
@media (max-width: 768px) {
  .score-section {
    flex-direction: column;
    gap: 24px;
  }

  .report-title h1 {
    font-size: 28px;
  }

  :deep(.ant-card-body) {
    padding: 16px;
  }
}
</style>

